/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package models.dados;

import javax.swing.JOptionPane;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author Wenderson
 */
public class HibernateUtil {
    
    private static SessionFactory sessionFactory =
            new Configuration().configure().buildSessionFactory();
    
    private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    
    public static Session getSession() {
        Session session = threadLocal.get();
        
        if (session == null || !session.isOpen()) {
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }
        
        return session;
    }
    
    public static void beginTransaction() {
        try {
            getSession().beginTransaction();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }
    
    public static void commitTransaction() {
        getSession().getTransaction().commit();
    }
    
    public static void rollBackTransaction() {
        getSession().getTransaction().rollback();
    }
    
    public static void closeSession() {
        getSession().close();
    }
}
